package com.fjwt.gz.task.qrshell;

import cn.hutool.http.HttpUtil;
import com.fjwt.gz.components.oss.config.OssYmlConfig;
import com.fjwt.gz.components.oss.model.OssFileConfig;
import com.fjwt.gz.core.utils.FileKit;
import com.google.zxing.WriterException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

/***
* 抽象类：  模板生成器
*
* @author wg
* @site https://pt.jdyd.xyz/
* @date 2022/1/18 12:33
*/
public abstract class AbstractGenerator {

    protected static final String DEFAULT_FONT = "微软雅黑"; // 微软雅黑   宋体

    @Autowired
    private OssYmlConfig ossYmlConfig;

    /**
     * 功能描述:生成图片的 BufferedImage
     *
     * @param configModelStr 自行转换
     * @param qrUrlContent 二维码内容
     * @param qrcId 码牌ID
     * @param isViewFlag 是否预览模式（将等比例缩小图片）
     * @Return: java.awt.image.BufferedImage
     * @Author: wangjie
     * @Date: 2022/1/18 15:52
     */

    public abstract BufferedImage genQrImgBuffer(String configModelStr, String qrUrlContent, Long qrcId, boolean isViewFlag) throws IOException, WriterException;


    protected BufferedImage getStaticImg(String img) throws IOException {
        return ImageIO.read(new ClassPathResource("static/images/qrshell" + img).getInputStream()); //
    }

    /** 下载文件进行缓存 & 获取图片 **/
    protected File downloadAndGetCacheFile(String url){

        // 下载地址为空
        if(StringUtils.isEmpty(url)){
            return null;
        }

        // String filePath = ossYmlConfig.getOss().getFilePublicPath() + File.separator + OssFileConfig.BIZ_TYPE.MARKETING + File.separator + FileKit.getUrlFileName(url);
        String filePath = ossYmlConfig.getOss().getFilePublicPath() + File.separator + OssFileConfig.BIZ_TYPE.DOWNLOAD + File.separator + FileKit.getUrlFileName(url);

        // 存在
        if(new File(filePath).exists()){
            return new File(filePath);
        }

        // 下载
        HttpUtil.downloadFile(url, filePath);
        return new File(filePath);
    }


    public static ByteArrayInputStream convertInputStream(BufferedImage bufferedImage) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "png", os);
        return new ByteArrayInputStream(os.toByteArray());
    }

}
